package ecoiot.com.testproject.view;

import android.annotation.SuppressLint;
import android.content.Context;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Path;
import android.support.annotation.Nullable;
import android.text.Layout;
import android.text.StaticLayout;
import android.text.TextPaint;
import android.util.AttributeSet;
import android.view.View;

/**
 * Created by developer on 17-11-8.
 */

public class TestView2 extends View {

    private Context mContext;

    public TestView2(Context context) {
        super(context);
        mContext = context;
    }

    public TestView2(Context context, @Nullable AttributeSet attrs) {
        super(context, attrs);
        mContext = context;
    }

    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        super.onMeasure(widthMeasureSpec, heightMeasureSpec);
    }

    @Override
    protected void onLayout(boolean changed, int left, int top, int right, int bottom) {
        super.onLayout(changed, left, top, right, bottom);
    }

    @SuppressLint("DrawAllocation")
    @Override
    protected void onDraw(Canvas canvas) {
        super.onDraw(canvas);

        Paint paint = new Paint();
        paint.setColor(Color.BLACK);
        //  设置格式为画线
        paint.setStyle(Paint.Style.STROKE);
        paint.setTextSize(30);

        TextPaint textPaint = new TextPaint(paint);

        String text1 = "abcdefghijklmnopqrstuvwxyz";
        String text2 = "Lorem Ipsum is simply dummy text of the printing and typesetting industry.";
        String text3 = "Lorem Ipsum \nis simply dummy text of the printing \nand typesetting industry.";

        Path path = new Path();
        path.moveTo(100,200);
        path.lineTo(200,300);
        path.lineTo(300,200);
        path.lineTo(400,300);

        //  使用canvas绘制文字时 坐标不是文字的左上角的坐标 而是文字左下角的左边
        canvas.drawText(text1,50,100,paint);
        canvas.drawPath(path,paint);
        //  这个方法是沿着一条path绘制文字 hOffset和vOffset是文字相对path的水平和竖直偏移量
        canvas.drawTextOnPath(text1,path,0,0,paint);

        //  使用drawText方法绘制文字只能绘制单行文字 超出的部分不会换行显示 也不能使用\n来换行
        //  StaticLayout类可以实现文字的换行
        //  width指的是长度超过多少就会自动换行 align指的是文字的对齐方向
        //  spacingmult 是行间距的倍数，通常情况下填 1 就好
        //  spacingadd 是行间距的额外增加值，通常情况下填 0 就好
        //  includeadd 是指是否在文字上下添加额外的空间，来避免某些过高的字符的绘制出现越界。
        StaticLayout layout1 = new StaticLayout(text2,textPaint,600,
                Layout.Alignment.ALIGN_NORMAL,
                1, 0, true);
        canvas.save();
        canvas.translate(50,350);
        layout1.draw(canvas);
        //  StaticLayout还可以直接使用\n换行
        StaticLayout layout2 = new StaticLayout(text3,textPaint,600,
                Layout.Alignment.ALIGN_NORMAL,
                1, 0, true);
        canvas.save();
        canvas.translate(0,100);
        layout2.draw(canvas);

    }


}
